package com.situ.mall.service.impl;

import com.situ.mall.mapper.CartMapper;
import com.situ.mall.mapper.OrderItemMapper;
import com.situ.mall.mapper.OrderMapper;
import com.situ.mall.pojo.Order;
import com.situ.mall.pojo.OrderItem;
import com.situ.mall.pojo.vo.CartVO;
import com.situ.mall.pojo.vo.OrderVO;
import com.situ.mall.service.IOrderService;
import com.situ.mall.util.SnowFlake;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

@Service
public class OrderServiceImpl implements IOrderService {
    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    private OrderMapper orderMapper;
    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    private CartMapper cartMapper;
    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    private OrderItemMapper orderItemMapper;
    @Autowired
    private SnowFlake snowFlake;

    @Override
    public boolean insert(Order order) {
        // order里有shippingId, userId, paymentType
        // 使用雪花算法生成order主键
        long id = snowFlake.nextId();
        order.setOrderNo(id);
        // 订单总金额
        BigDecimal payment = BigDecimal.valueOf(0.0);
        List<CartVO> cartVOList = cartMapper.selectByUserIdAndChecked(order.getUserId());
        for (CartVO cartVO : cartVOList) {
            BigDecimal productPrice = cartVO.getProductPrice();
            Integer quantity = cartVO.getQuantity();
            OrderItem orderItem = new OrderItem();
            orderItem.setOrderNo(id);
            orderItem.setUserId(order.getUserId());
            orderItem.setProductId(cartVO.getProductId());
            orderItem.setProductName(cartVO.getProductName());
            orderItem.setProductImage(cartVO.getProductMainImage());
            orderItem.setCurrentUnitPrice(productPrice);
            orderItem.setQuantity(quantity);
            // 计算价格
            BigDecimal totalPrice = productPrice.multiply(BigDecimal.valueOf(quantity));
            orderItem.setTotalPrice(totalPrice);
            orderItemMapper.insertSelective(orderItem);
            payment = payment.add(totalPrice);
            // 删除购物车里当前的商品
            cartMapper.deleteByPrimaryKey(cartVO.getId());
        }
        order.setPayment(payment);
        return orderMapper.insertSelective(order) > 0;
    }

    @Override
    public List<OrderVO> selectByUserId(Integer id) {
        return orderMapper.selectByUserId(id);
    }
}
